package ru.gerunn.silent.server;

import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

import ru.gerunn.silent.common.Reader;
import ru.gerunn.silent.common.SSLSocketReader;
import ru.gerunn.silent.common.SSLSocketWriter;
import ru.gerunn.silent.common.Writer;
import ru.gerunn.silent.message.Message;
import ru.gerunn.silent.trash.User;

public class Session implements Runnable {

	private Writer writer;
	private Reader reader;
	private SSLSession sslSession;
	private Server server;
	private User user;

	public Session(SSLSocket socket, Server server, User user) {
		this.writer = new SSLSocketWriter(socket);
		this.reader = new SSLSocketReader(socket);
		this.setSslSession(socket.getSession());
		this.setServer(server);
		this.setUser(user);
	}

	public void run() {
		this.commitSession();
		Message message = null;
		while ((message = this.reader.read()) != null) {
			for (Session session : this.getServer().getSessions()) {
				session.getWriter().write(message);
			}
		}
	}

	public SSLSession getSslSession() {
		return sslSession;
	}

	public void setSslSession(SSLSession sslSession) {
		this.sslSession = sslSession;
	}

	public Server getServer() {
		return server;
	}

	public void setServer(Server server) {
		this.server = server;
	}

	synchronized private void commitSession() {
		this.getServer().getSessions().add(this);
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Writer getWriter() {
		return writer;
	}

	public void setWriter(Writer writer) {
		this.writer = writer;
	}

	public Reader getReader() {
		return reader;
	}

	public void setReader(Reader reader) {
		this.reader = reader;
	}

}
